package com.kasa.zto.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class Tools
{
    /**
     * 字节数字转换成int
     *
     * @param b
     *            要转换的字节数组
     * @return 转换后的int类型
     */
    public static int byte2int(byte[] b)
    {
        return byte2int(b, 0);
    }

    /**
     * 字节数字转换成int
     *
     * @param b
     *            要转换的字节数组
     * @param offset
     *            字节数字起始位置
     * @return 转换后的int类型
     */
    public static int byte2int(byte[] b, int offset)
    {
        return b[3 + offset] & 0xff | (b[2 + offset] & 0xff) << 8
            | (b[1 + offset] & 0xff) << 16 | (b[0 + offset] & 0xff) << 24;
    }
    
    public static byte[] gZip(byte[] data) throws IOException
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(bos);
        gzip.write(data);
        gzip.finish();
        gzip.close();
        byte[] b = bos.toByteArray();
        bos.close();

        gzip = null;
        bos = null;
        return b;
    }

    public static byte[] unGZip(byte[] data) throws IOException
    {
        GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(data));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int num = -1;
        byte[] buf = new byte[1024];
        while ((num = gzip.read(buf, 0, buf.length)) != -1)
        {
            baos.write(buf, 0, num);
        }
        byte[] b = baos.toByteArray();
        baos.flush();
        baos.close();
        gzip.close();

        buf = null;
        baos = null;
        gzip = null;
        return b;
    }
}